package org.easy.elasticsearch;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.util.ObjectUtils;

@Configuration
@EnableConfigurationProperties({ElasticsearchProperties.class})
//@ConditionalOnProperty(prefix = ElasticsearchProperties.PREFIX, name = "endpoints", havingValue = "true")
public class ElasticsearchAutoConfiguration {

    private final ElasticsearchProperties elasticsearchProperties;

    public ElasticsearchAutoConfiguration(ElasticsearchProperties elasticsearchProperties) {
        this.elasticsearchProperties = elasticsearchProperties;
    }


    @Bean
    public CommonElasticsearchTemplate commonElasticsearchTemplate() {
        return new CommonElasticsearchTemplate(elasticsearchRestTemplate());
    }

    public ElasticsearchRestTemplate elasticsearchRestTemplate() {
        ClientConfiguration.MaybeSecureClientConfigurationBuilder build = ClientConfiguration.builder()
                .connectedTo(elasticsearchProperties.getEndpoints());

        if (!ObjectUtils.isEmpty(elasticsearchProperties.getUsername()) && !ObjectUtils.isEmpty(elasticsearchProperties.getPassword())) {
            build.withBasicAuth(elasticsearchProperties.getUsername(), elasticsearchProperties.getPassword());
        }

        ClientConfiguration clientConfiguration = build.build();

        RestHighLevelClient client = RestClients.create(clientConfiguration).rest();
        return new ElasticsearchRestTemplate(client);
    }


}
